<template>
  <div class="page">
    <h2>培训与预防</h2>

    <div class="controls">
      <el-input v-model="q" placeholder="按课程/讲师搜索" clearable style="flex:1" @clear="onClear" />

      <el-select v-model="filterType" placeholder="全部类型" style="width:180px">
        <el-option label="全部类型" :value="''" />
        <el-option label="技能训练" value="skill" />
        <el-option label="心理教育" value="psy" />
        <el-option label="演练" value="drill" />
      </el-select>

      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="openModal()">新增课程</el-button>
        <el-button @click="exportCSV">导出课程</el-button>
      </div>
    </div>

    <el-table :data="filtered" stripe border style="width:100%;margin-top:12px" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="课程/活动" />
      <el-table-column prop="type" label="类型" width="120">
        <template #default="{ row }">{{ mapType(row.type) }}</template>
      </el-table-column>
      <el-table-column prop="trainer" label="讲师/负责人" width="160" />
      <el-table-column prop="date" label="时间" width="180" />
      <el-table-column prop="location" label="地点" width="140" />
      <el-table-column prop="attendance" label="出勤/计划" width="140" />
      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button size="small" @click="view(row.id)">查看</el-button>
          <el-button size="small" @click="openModal(row.id)" style="margin-left:8px">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteOne(row.id)" style="margin-left:8px">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:8px;display:flex;gap:8px;align-items:center">
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
      <div style="flex:1"></div>
      <div class="muted">已选：{{ selectedIds.length }} 项</div>
    </div>

    <el-dialog :title="editingId ? '编辑课程' : '新增课程'" v-model="showModal" width="720px">
      <el-form :model="form" label-width="120px">
        <el-form-item label="课程/活动">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="form.type" style="width:200px">
            <el-option label="技能训练" value="skill" />
            <el-option label="心理教育" value="psy" />
            <el-option label="演练" value="drill" />
          </el-select>
        </el-form-item>
        <el-form-item label="讲师/负责人">
          <el-input v-model="form.trainer" />
        </el-form-item>
        <el-form-item label="时间">
          <el-date-picker v-model="form.date" type="datetime" placeholder="选择时间" style="width:220px" />
        </el-form-item>
        <el-form-item label="地点">
          <el-input v-model="form.location" />
        </el-form-item>
        <el-form-item label="计划/出勤">
          <el-input v-model="form.attendance" placeholder="例如：20/24" />
        </el-form-item>
        <el-form-item label="说明">
          <el-input type="textarea" v-model="form.notes" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const DEFAULT_DATA = [
  { id:1, title:'创伤后应激识别与处理', type:'psy', trainer:'李心理师', date:'2025-10-10 09:00', location:'多功能厅', attendance:'18/20', notes:'针对救援相关创伤的识别与短期干预' },
  { id:2, title:'现场心理急救演练', type:'drill', trainer:'赵教官', date:'2025-11-05 14:00', location:'训练场', attendance:'24/24', notes:'结合实战模拟进行压力管理训练' }
];

const data = ref([]);
const q = ref('');
const filterType = ref('');
const selectedRows = ref([]);
const selectedIds = ref([]);
const showModal = ref(false);
const editingId = ref(null);
const form = reactive({ title:'', type:'psy', trainer:'', date:'', location:'', attendance:'', notes:'' });

onMounted(()=>{ load(); });
function load(){ data.value = JSON.parse(JSON.stringify(DEFAULT_DATA)); }

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return data.value.filter(d=>{
    if(qq && !( (d.title||'').toLowerCase().includes(qq) || (d.trainer||'').toLowerCase().includes(qq) )) return false;
    if(filterType.value && d.type !== filterType.value) return false;
    return true;
  });
});

watch(selectedRows, v=>{ selectedIds.value = v.map(i=>i.id); });
function onSelectionChange(rows){ selectedRows.value = rows; }

function openModal(id){ editingId.value = id || null; if(id){ const it = data.value.find(x=>x.id===id); if(it) Object.assign(form, JSON.parse(JSON.stringify(it))); } else{ Object.assign(form,{title:'',type:'psy',trainer:'',date:'',location:'',attendance:'',notes:''}); } showModal.value = true; }
function closeModal(){ showModal.value = false; editingId.value = null; }
function save(){ if(!form.title || !form.trainer){ ElMessage.warning('课程名称与讲师为必填项'); return; } if(editingId.value){ const it = data.value.find(x=>x.id===editingId.value); if(it) Object.assign(it, JSON.parse(JSON.stringify(form))); } else{ const nid = (data.value.reduce((s,i)=>Math.max(s,i.id),0) || 0) + 1; data.value.push(Object.assign({ id:nid }, JSON.parse(JSON.stringify(form)))); } showModal.value=false; ElMessage.success('保存成功'); }

function mapType(t){ return t==='psy' ? '心理教育' : t==='skill' ? '技能训练' : '演练'; }

function view(id){ const it = data.value.find(x=>x.id===id); if(it){ ElMessage.info(`${it.title} ${mapType(it.type)} ${it.date}`); } }

function deleteOne(id){ ElMessageBox.confirm('确认删除该课程？','删除确认',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(x=>x.id!==id); ElMessage.success('已删除'); })
  .catch(()=>{});
}
function batchDelete(){ const ids = selectedIds.value.slice(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessageBox.confirm(`确认删除 ${ids.length} 条记录？`,'批量删除',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(d=>!ids.includes(d.id)); selectedIds.value = []; selectedRows.value = []; ElMessage.success('已删除'); })
  .catch(()=>{});
}

function exportCSV(){ const csv = [ ['id','title','type','trainer','date','location','attendance','notes'], ...data.value.map(d=>[d.id,d.title,d.type,d.trainer,d.date,d.location,d.attendance||'',d.notes||'']) ]; const csvContent = csv.map(r=>r.map(cell=>`"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n'); const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download='firefighter_training.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); }

function onClear(){ }
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
</style>